<!--
 * @Descripttion: 编辑点赞集福活动
 * @Author: xiao li
 * @Date: 2020-12-07 11:40:09
 * @LastEditors: xiao li
 * @LastEditTime: 2021-11-23 15:45:02
-->
<template>
  <div class="lb-add-classify">
    <top-nav :title="navTitle" :isBack="true" />
    <div class="form-search">
      <div style="height: 40px"></div>

      <el-form
        @submit.native.prevent
        :model="subForm"
        ref="subForm"
        :rules="subFormRules"
        label-width="120px"
      >
        <el-form-item label="选择集福课程" prop="class_id">
          <el-select
            :disabled="subForm.id ? true : false"
            v-model="subForm.class_id"
            placeholder="请选择集福课程"
          >
            <el-option
              v-for="item in courseList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
              :disabled="item.is_atv === 1 ? true : false"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="封面图" prop="cover">
          <lb-cover
            :fileList="subForm.cover"
            @selectedFiles="getCover"
          ></lb-cover>
          <lb-tool-tips>图片建议尺寸: 750 * 450</lb-tool-tips>
        </el-form-item>
        <el-form-item label="集福人数" prop="num">
          <el-input
            v-model.number="subForm.num"
            placeholder="请输入集福人数"
          ></el-input>
        </el-form-item>
        <el-form-item label="活动价" prop="price_type">
          <el-radio-group v-model="subForm.price_type">
            <el-radio :label="0">免费</el-radio>
            <el-radio :label="1">自定义价格</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="" prop="price" v-if="subForm.price_type === 1">
          <el-input placeholder v-model="subForm.price">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="活动时间" prop="atv_time">
          <el-input placeholder v-model="subForm.atv_time">
            <template slot="append">秒</template>
          </el-input>
        </el-form-item>
        <el-form-item label="参与必授权" prop="auth">
          <el-checkbox-group @change="changeCheckBox" v-model="checkList">
            <div
              v-for="(item, index) in authList"
              :key="index"
              :style="{
                display: 'inline-block',
                marginLeft: index === 0 ? 0 : '15px'
              }"
            >
              <el-checkbox :label="item.title"></el-checkbox>
              <lb-tool-tips v-if="item.tips">{{ item.tips }}</lb-tool-tips>
            </div>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="排序值" prop="top">
          <el-input-number
            class="lb-input-number"
            v-model="subForm.top"
            :controls="false"
            :precision="0"
            :min="0"
            placeholder="请输入排序值"
          ></el-input-number>
          <lb-tool-tips>值越大, 排序越靠前</lb-tool-tips>
        </el-form-item>
        <el-form-item label="活动规则" prop="text">
          <lb-ueditor
            v-model="subForm.text"
            :destroy="true"
            :ueditorType="3"
          ></lb-ueditor>
        </el-form-item>
        <el-form-item>
          <lb-button type="primary" @click="submitInfo">{{
            $t('action.submit')
          }}</lb-button>
          <lb-button @click="goBack">{{ $t('action.back') }}</lb-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    let validatePrice = (rule, value, callback) => {
      if (this.subForm.price_type === 1) {
        if (!/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/.test(value) || value < 0.01) {
          callback(new Error('请输入正确的金额，最多保留两位小数'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    let validateTime = (rule, value, callback) => {
      if (!/^\+?[1-9]\d*$/.test(value)) {
        callback(new Error('请输入大于0的数字'))
      } else {
        callback()
      }
    }
    let validateAuth = (rule, value, callback) => {
      if (this.subForm.auth_wx === 0 && this.subForm.auth_mobile === 0) {
        callback(new Error('请选择参与必授权'))
      } else {
        callback()
      }
    }
    return {
      id: '',
      navTitle: '',
      courseList: [],
      authTips: '选中后授权所选内容才能参与活动',
      checkList: [],
      authList: [
        {
          title: '微信信息/头像',
          key: 'auth_wx'
        },
        {
          title: '手机号',
          key: 'auth_mobile',
          tips: '用户需授权所选内容才能参与活动'
        }
      ],
      subForm: {
        id: 0,
        class_id: '',
        cover: '',
        num: '',
        price_type: 0,
        price: '',
        atv_time: '',
        auth_wx: 0,
        auth_mobile: 0,
        text: '',
        top: 0,
        status: 1
      },
      subFormRules: {
        class_id: { required: true, type: 'number', message: '请选择集福课程', trigger: 'blur' },
        cover: { required: true, type: 'array', message: '请上传图片', trigger: 'change' },
        price_type: { required: true },
        price: { validator: validatePrice, trigger: 'blur' },
        num: { required: true, validator: validateTime, trigger: 'blur' },
        atv_time: { required: true, validator: validateTime, trigger: 'blur' },
        auth: { required: true, validator: validateAuth, trigger: 'blur' },
        top: { required: true, message: '请输入排序值', trigger: 'blur' },
        text: { required: true, type: 'string', message: '请输入活动规则', trigger: 'blur' }
      }
    }
  },
  async created () {
    let { id } = this.$route.query
    await this.getClassList()
    if (id) {
      this.subForm.id = id
      await this.getDetail(id)
    }
    this.navTitle = this.$t(id ? 'menu.PayclassAtvEdit' : 'menu.PayclassAtvAdd')
  },
  methods: {
    async getClassList () {
      let { code, data } = await this.$api.payclassClassSelect()
      if (code !== 200) return
      this.courseList = data
    },
    changeCheckBox (e) {
      this.authList.map(item => {
        this.subForm[item.key] = e.includes(item.title) ? 1 : 0
      })
    },
    async getDetail (id) {
      let { code, data } = await this.$api.payclassAtvInfo({ id })
      if (code !== 200) return
      let checkItem = []
      this.authList.map(item => {
        if (data[item.key] === 1) {
          checkItem.push(item.title)
        }
      })
      this.checkList = checkItem

      data.cover = [{ url: data.cover }]
      for (let key in this.subForm) {
        this.subForm[key] = data[key]
      }
    },
    /**
     * @method 获取课程封面图
     */
    getCover (img) {
      this.subForm.cover = img
    },
    /**
     * @method 添加/编辑
     */
    submitInfo () {
      let flag = true
      this.$refs['subForm'].validate(valid => {
        if (!valid) flag = false
      })
      if (flag) {
        let subForm = JSON.parse(JSON.stringify(this.subForm))
        let modelMethod = subForm.id ? 'payclassAtvUpdate' : 'payclassAtvAdd'
        subForm.cover = subForm.cover[0].url
        this.$api[modelMethod](subForm).then(res => {
          if (res.code === 200) {
            this.$message.success(this.$t(subForm.id ? 'tips.successRev' : 'tips.successSub'))
            this.goBack()
          }
        })
      }
    },

    /**
     * @method 返回上一页
     */
    goBack () {
      this.$router.back(-1)
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-add-classify {
  width: 100%;
  .form-search {
    padding: 20px;
    .el-form {
      width: 100%;
      .el-form-item {
        margin-bottom: 24px;
        .el-select,
        .el-input-number,
        .el-input {
          width: 300px;
        }
      }
      .last-form-item {
        margin-top: 30px;
      }
      .item-tips {
        margin-left: 120px;
        margin-bottom: 24px;
        color: #999999;
      }
    }
  }
}
</style>
